package com.zkw.service.impl;

import com.zkw.dao.BookDao;
import com.zkw.domain.Book;
import com.zkw.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;
    @Autowired
    private RedisTemplate redisTemplate;

    @Cacheable(cacheNames = "book")
    @Override
    public Book findById(int id) {
        Optional<Book> optional = bookDao.findById(id);
        if(optional.isPresent()){
            Book book = optional.get();
            return book;
        }else {
            return null;
        }

    }

    //@Cacheable(cacheNames = "book")
    @Override
    public Book findByIdAPI(int id) {
        Object obj = redisTemplate.opsForValue().get("bookapi_" + id);
        if(obj !=null){
            return (Book)obj;
        }else {
            Optional<Book> optional = bookDao.findById(id);
            if(optional.isPresent()){
                Book book = optional.get();
                redisTemplate.opsForValue().set("bookapi_"+id, book, 100, TimeUnit.SECONDS);
                return book;
            }else {
                return null;
            }
        }
    }

    @Override
    public Book updateBook(Book book) {
        bookDao.updateBook(book.getDescription(),book.getId());
        return book;
    }

    @Override
    public void deleteBook(int id) {
        bookDao.deleteById(id);
    }
}
